/**
 * 给视频添加时长、大小信息
 */
const low = require('lowdb')
const FileSync = require('lowdb/adapters/FileSync')

const dataBaseDir = 'E:/code/electron/dream/src/data/'

const db = low(new FileSync(`${dataBaseDir}/movie.json`))

const movies = db.read()
    .get('movies')
    .value()

const ffmpegPath = require('@ffmpeg-installer/ffmpeg')
const ffprobePath = require('@ffprobe-installer/ffprobe')
const ffmpeg = require('fluent-ffmpeg')
ffmpeg.setFfmpegPath(ffmpegPath.path)
ffmpeg.setFfprobePath(ffprobePath.path)

updateMoviesInfo(movies.slice(30))

async function updateMoviesInfo(updateMovies) {
    let updateCount = 0
    let doneCount = 0
    for (let movie of updateMovies) {
        console.log(movie.name)
        const star = movie.star ? `${movie.star}/` : ''
        const videoRootDir = `${movie.rootDir}${star}${movie.year}.${movie.name}/`
        for (let dreamVideo of movie.dreamVideos) {
            console.log('--', dreamVideo.name)
            if (!dreamVideo.size) {
                const video = `${videoRootDir}${dreamVideo.video}`
                const videoInfo = await getVideoInfo(video)
                if (videoInfo) {
                    Object.assign(dreamVideo, videoInfo)
                    updateCount++
                } else {
                    console.log(dreamVideo)
                }
            } else {
                doneCount++
            }
        }
    }
    if (updateCount > 0) {
        db.read()
            .set('movies', movies)
            .write()
    }
    console.log('updateCount', updateCount)
    console.log('doneCount', doneCount)
}

async function getVideoInfo(video) {
    return new Promise((resolve, reject) => {
        ffmpeg.ffprobe(video, (err, data) => {
            if (data) {
                resolve({
                    'duration': data.format.duration,
                    'durationF': formatSeconds(data.format.duration),
                    'size': data.format.size,
                    'sizeF': formatBytes(data.format.size),
                })
            } else {
                resolve(null)
            }
        })
    })
}

function formatSeconds(seconds) {
    // 四舍五入取整
    seconds = Math.round(seconds)
    // 计算小时、分钟和秒
    const hrs = Math.floor(seconds / 3600)
    const mins = Math.floor((seconds % 3600) / 60)
    const secs = seconds % 60

    // 将小时、分钟和秒格式化为字符串
    const h = hrs.toString().padStart(2, '0')
    const m = mins.toString().padStart(2, '0')
    const s = secs.toString().padStart(2, '0')

    // 组合成最终的时间字符串
    return `${h}:${m}:${s}`
}

function formatBytes(bytes, decimals = 2) {
    if (bytes === 0) return '0'

    const k = 1024
    const sizes = ['B', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y']

    const i = Math.floor(Math.log(bytes) / Math.log(k))
    return (
        parseFloat((bytes / Math.pow(k, i)).toFixed(decimals)) + sizes[i]
    )
}
